package io.noties.markwon.app.utils;

import com.noties.markwon.utils.LogUtils;

import io.noties.markwon.app.sample.Sample;
import io.noties.markwon.sample.annotations.MarkwonArtifact;
import java.io.IOException;
import java.io.InputStream;
import ohos.app.Context;
import ohos.global.resource.RawFileEntry;

public class SampleUtilsKt {

    private static final String SAMPLE_PREFIX = "io.noties.markwon.app.";

    public static String getDisplayName(MarkwonArtifact markwonArttifact) {
        return String.format("@%1s", markwonArttifact==null?"-":markwonArttifact.artifactName());
    }

    public static String getTagDisplayName(String name) {
        return String.format("#%1s", name);
    }

    public static String loadReadMe(Context context) {
        RawFileEntry rawFileEntry = context.getResourceManager().getRawFileEntry("resources/rawfile/README.md");
        try {
            InputStream inputStream = rawFileEntry.openRawFile();
            return InputStreamUtils.readStringAndClose(inputStream);
        } catch (Exception ignored) {

        }
        return "";
    }

    public static Sample.Code readCode(Context context, Sample sample) {
        // keep sample and nested directories
        String pathTemp = sample.getJavaClassName();
        if (pathTemp.startsWith(SAMPLE_PREFIX)) {
            pathTemp = pathTemp.substring(SAMPLE_PREFIX.length());
        }
        String path = pathTemp.replace('.', '/');
        LogUtils.i("path:" + path);
        // now, we have 2 possibilities ->  Java
        Sample.Language language = Sample.Language.JAVA;
        return new Sample.Code(language, obtain(context,path + ".java"));
    }


    private static String obtain(Context context, String path) {
        LogUtils.i("obtain path:" + path);

        RawFileEntry rawFileEntry = context.getResourceManager()
            .getRawFileEntry("resources/rawfile/"+path);
        try (InputStream inputStream = rawFileEntry.openRawFile()) {
            return InputStreamUtils.readStringAndClose(inputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
